package com.agriculture.monitor.service.impl;

import com.agriculture.monitor.dto.MenuDataDTO;
import com.agriculture.monitor.dto.RoleMenuDTO;
import com.agriculture.monitor.entity.Menu;
import com.agriculture.monitor.entity.RoleMenu;
import com.agriculture.monitor.mapper.MenuMapper;
import com.agriculture.monitor.mapper.RoleMenuMapper;
import com.agriculture.monitor.service.IMenuService;
import com.agriculture.monitor.util.TreeUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author admin
 * @since 2024-03-21
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

    @Autowired
    RoleMenuMapper roleMenuMapper;

    @Override
    public List<Menu> tree(Menu menu) {
        List<Menu> menus= baseMapper.findList(menu.getRoleId());
        menus = TreeUtils.buildTree(menus, null);
        return menus;
    }

    @Override
    public MenuDataDTO checkRole(Integer roleId) {

        List<RoleMenu> roleMenus = roleMenuMapper.selectList(new LambdaQueryWrapper<RoleMenu>().eq(RoleMenu::getRoleId, roleId));

        Map<Integer, Integer> map = roleMenus.stream().collect(Collectors.toMap(RoleMenu::getMenuId, RoleMenu::getRoleId));

        List<Menu> menus = this.list();

        for (Menu menu : menus) {
            menu.setChecked(map.containsKey(menu.getId()) ? 1 : 0);
        }
        menus = TreeUtils.buildTree(menus, null);

        return MenuDataDTO.builder().menuList(menus).checkMenuIdList(new ArrayList<>(map.keySet())).build();
    }

    @Override
    @Transactional
    public Boolean saveRoleMenu(RoleMenuDTO roleMenuDTO) {
        roleMenuMapper.delete(new LambdaUpdateWrapper<RoleMenu>().eq(RoleMenu::getRoleId, roleMenuDTO.getRoleId()));
        for (Integer menuId : roleMenuDTO.getMenuIds()) {
            RoleMenu menu = RoleMenu.builder().menuId(menuId).roleId(roleMenuDTO.getRoleId()).build();
            roleMenuMapper.insert(menu);
        }
        return true;
    }


}
